package com.example.zx_springboot.controller;

import com.example.zx_springboot.entity.ZxResource;
import com.example.zx_springboot.entity.ZxUser;
import com.example.zx_springboot.entity.Zxloss;
import com.example.zx_springboot.jwt.JWTUtils;
import com.example.zx_springboot.mapper.ZxUserMapper;
import com.example.zx_springboot.mapper.Zx_RoleMapper;
import com.example.zx_springboot.service.ZxUserService;
import com.example.zx_springboot.utils.Result;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class ZxUserController {
    @Autowired
    private ZxUserService userService;
    @Autowired
    private Zx_RoleMapper zxRoleMapper;
    @Autowired
    private ZxUserMapper loginUserMapper;
    @Autowired
    private ZxUserMapper zxUserMapper;

    @GetMapping("/getall")//设置查询方式
    public List<ZxUser> getall()//通过@PathVariable获取id的路径
    {
        List<ZxUser> zxUser = userService.getall();
        return zxUser;
    }

//    @PutMapping("/user/login")
//    public Map<String,Object> login(@RequestBody  ZxUser user) {
//        log.info("user",user);
//        log.info("用户名: [{}]", user.getUserName());
//        log.info("密码: [{}]", user.getUserPwd());
//        Map<String, Object> map = new HashMap<>();
//        try {
//            ZxUser userDB = userService.login(user);
//            if(userDB!=null){
//                Map<String, Object> payload = new HashMap<>();
//                payload.put("id", userDB.getUser_id());
//                payload.put("name", userDB.getUserName());
//                //生成JWT的令牌
//                String token = JWTUtils.getToken(payload);
//                map.put("state", true);
//                map.put("msg", "认证成功");
//                map.put("token", token);//响应token
//            }else{
//                map.put("state", false);
//                map.put("msg", "用户名或者密码错误");
//            }
//
//        } catch (Exception e) {
//            map.put("state", false);
//            map.put("msg", e.getMessage());
//        }
//        return map;
//    }

@PostMapping("/login")
public ZxUser lg(@RequestBody ZxUser zxUser){
        ZxUser a=userService.login(zxUser);
        return a;
}

    @PostMapping("/user/login")
    public Result login(@RequestBody  ZxUser user) {
        log.info("user",user);
        log.info("用户名: [{}]", user.getUserName());
        log.info("密码: [{}]", user.getUserPwd());
//        Map<String, Object> map = new HashMap<>();
        try {
            ZxUser userDB = userService.login(user);
            System.out.println(userDB);
            if(userDB!=null){
                Map<String, Object> payload = new HashMap<>();
                payload.put("id", userDB.getUser_id());
                payload.put("name", userDB.getUserName());
                //生成JWT的令牌
                String token = JWTUtils.getToken(payload);
               // map.put("state", true);
              //  map.put("msg", "认证成功");
              //  map.put("token", token);//响应token
                System.out.println(token);
                return Result.ok(token);
            }else{
               // map.put("state", false);
               // map.put("msg", "用户名或者密码错误");
                return Result.err("失败");
            }

        } catch (Exception e) {
            Map<String, Object> map = new HashMap<>();
            map.put("state", false);
            map.put("msg", e.getMessage());
            Result.Fail(map);
        }
        return null;
    }
    @GetMapping("/login/menu")
    public List<ZxResource>  loginrole(@RequestParam("userName") String userName){
         ZxUser zxUser=  userService.person(userName);
         String role_name=zxUser.getRole();
         Integer role_id= zxRoleMapper.loginrole( role_name).getRole_id();  //role_id
        List<Integer> resource_ids= loginUserMapper.loginresourceid(role_id);//resource_id数组
        List<ZxResource> loginmenus = new ArrayList<>();
        for( Integer resource_id:resource_ids){
            List<ZxResource>  menus=  zxUserMapper.loginmenus(resource_id);
            loginmenus.addAll(menus);
        }
        List<ZxResource> parentNode = loginmenus.stream().filter(menu -> menu.getPid() == 0).toList();

        for (ZxResource menu : parentNode) {
            // 筛选所有数据中pid=父级id的数据就是二级菜单
            menu.setChildren(loginmenus.stream().filter(m -> menu.getResource_id()==(m.getPid())).distinct().collect(Collectors.toList()));}

          return parentNode;
    }

    @PostMapping("/user/register")
    public String register(@RequestBody ZxUser zxUser){
        ZxUser isregister=userService.isregister(zxUser);
        if(isregister==null){
            userService.adduser(zxUser);
            return "register success";
        }else {
            return "register error";
        }


    }

    @GetMapping("/findByPage")
    public PageInfo findAll(@RequestParam("pageNum") Integer pageNum,
                            @RequestParam("pageSize") Integer pageSize,
                            @RequestParam("userName") String userName) {
        return userService.findByPage(pageNum, pageSize,userName);
    }


    @PostMapping("/adduser")
    public String adduser(@RequestBody ZxUser zxUser) {
        userService.adduser(zxUser);
        return "adduser success";
    }

    @DeleteMapping("/deluser")
    public String deleteUser(@RequestParam("user_id") int user_id) {
        userService.deleteuser(user_id);
        return "delete success";
    }

    @PostMapping("/updateuser")
    public ZxUser update(@RequestBody ZxUser zxUser) {
        ZxUser zxUser_tmp = userService.UpdateUser(zxUser);
        return zxUser_tmp;
    }

    @GetMapping("/getuser/{id}")//设置查询方式
    public ZxUser getUser(@PathVariable("id") Integer id)//通过@PathVariable获取id的路径
    {
        ZxUser zxUser = userService.getUserById(id);
        return zxUser;
    }
    @PostMapping("/delusers")
    public String delusers(@RequestBody List<Integer> ids){
        userService.deleteusers(ids);

        return "delete success";
    }
    @GetMapping("/selectname")
    public List<ZxUser> selectname(@RequestParam("userName") String userName){
       userName = "%" + userName + "%";
        List<ZxUser>  user=userService.selectname(userName);
       return user;
    }
    @GetMapping("/person")
    public ZxUser person(@RequestParam("userName") String userName){
    return userService.person(userName);

    }
    @PostMapping("/personpwd")
    public ZxUser personpwd(@RequestBody ZxUser zxUser){
        return userService.personpwd(zxUser);
    }
    @PostMapping("/updateperson")
    public String updateperson(@RequestBody ZxUser zxUser) {
        userService.Updateperson(zxUser);
        return "edit success";
    }
    @GetMapping("/upadtepwd")
    public String updatepwd(@RequestParam("newpwd")String newpwd,
                            @RequestParam("username")String username){
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("newpwd", newpwd);
        paramMap.put("username", username);
        userService.Updatepersonpwd(paramMap);
        return "edit success";
    }

}